// https://github.com/peterhuang007/weixinFileToaliyun
/**
 * config.js
 * module.exports = {
    AccessKeyId:"", 
    AccessKeySecret:"", 
    aliyunServerURL:"https://xxxx.oss-cn-beijing.aliyuncs.com",
}
 */
const env = require('../config/config.js');
const Base64 = require('./Base64.js');
require('./hmac.js');
require('./sha1.js');
const Crypto = require('./crypto.js');
const timeout = 87600;

/**
 * filePath 小程序要上传视频的路径
 * dir 文件保存路径
 * objectId 文件唯一id
 * success 上传成功callback
 * error 上传失败callback
 * onProgress 支持版本 >= 1.4.0
 */
const uploadFile = function ({filePath, dir, objectId, success, error,onProgress}) {
    if (!filePath || filePath.length < 9) {
        wx.showModal({
            title: '视频错误',
            content: '请重试',
            showCancel: false,
        })
        return;
    }
    if(!objectId) {
        console.error("请传入objectId,唯一ID")
        return;
    }
    const extName = getExtName(filePath) ? "."+getExtName(filePath) :"";
    const dirPath = dir?dir+"/":"";
    const aliyunFileKey = dirPath + objectId + extName;
    const aliyunServerURL = env.aliyunServerURL;
    const accessid = env.AccessKeyId;
    const policyBase64 = getPolicyBase64();
    const signature = getSignature(policyBase64);

    console.log('aliyunFileKey=', aliyunFileKey);
    let header = {};
    const uploadTask = wx.uploadFile({
        header,
        url: aliyunServerURL, //仅为示例，非真实的接口地址
        filePath: filePath,
        name: 'file',
        formData: {
            'key': aliyunFileKey,
            'OSSAccessKeyId': accessid,
            'policy': policyBase64,
            'Signature': signature,
            'x-oss-security-token': env.SecurityToken,
            'success_action_status': '200',
        },
        success: function (res) {
            if (res.statusCode != 200) {
                error(new Error('上传错误:' + JSON.stringify(res)))
                return;
            }
            console.log('上传视频成功', res)
            success({
                baseUrl:aliyunServerURL,
                filaPath:aliyunFileKey
            });
        },
        fail: function (err) {
            err.wxaddinfo = aliyunServerURL;
            error(err);
        },
    });
    if(onProgress && typeof onProgress == 'function' && uploadTask) {
        uploadTask.onProgressUpdate(onProgress);
    } 
    return uploadTask;
}

const getPolicyBase64 = function () {
    let date = new Date();
    date.setHours(date.getHours() + timeout);
    let srcT = date.toISOString();
    const policyText = {
        "expiration": srcT, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了 指定了Post请求必须发生在2020年01月01日12点之前("2020-01-01T12:00:00.000Z")。
        "conditions": [
            ["content-length-range", 0, 350 * 1024 * 1024] // 设置上传文件的大小限制,350M
        ]
    };

    const policyBase64 = Base64.encode(JSON.stringify(policyText));
    return policyBase64;
}

const getSignature = function (policyBase64) {
    const accesskey = env.AccessKeySecret;

    const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
        asBytes: true
    });
    const signature = Crypto.util.bytesToBase64(bytes);

    return signature;
}

const getExtName = (file) => {
    let lastIndex = file.lastIndexOf(".");
    if(lastIndex >= 0) {
        return file.substr(lastIndex+1);
    } else {
        return "";
    }
}


module.exports = uploadFile;